package com.src.xyzk_personal.Service;

import android.util.Log;

import com.src.xyzk_personal.config.LogFile;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;


/**
 * 收集异常信息
 */
public class CrashHandler implements UncaughtExceptionHandler {
	private static UncaughtExceptionHandler mDefaultHandler;
	private LogFile m_log = null;

	/**
	 * 初始化,注册Context对象,
	 * 获取系统默认的UncaughtException处理器,可以将部分操作交给默认处理器处理
	 * 设置该CrashHandler为程序的默认处理器
	 */
	public static void init() {
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		Thread.setDefaultUncaughtExceptionHandler(mDefaultHandler);
	}


	@Override
	public void uncaughtException(Thread t, Throwable e) {
		Log.e("crash","dsa");
		if (e != null && e.getLocalizedMessage()!= null){//收集设备信息
			saveCrashInfoToFile(e);
		}
		if (mDefaultHandler != null) {//收集完信息后，交给系统自己处理崩溃
			mDefaultHandler.uncaughtException(t, e);
		}
	}

	/**
	 * 保存错误信息到文件中
	 * @param ex
	 * @return
	 */
	private void saveCrashInfoToFile(Throwable ex) {
		Writer info = new StringWriter();
		PrintWriter printWriter = new PrintWriter(info);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		String result = info.toString();
		printWriter.close();
		m_log.PrintLog(result);
	}
}
